package com.tensquare.notice.listener;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.rabbitmq.client.Channel;
import com.tensquare.entity.Result;
import com.tensquare.entity.StatusCode;
import com.tensquare.notice.handler.MyWebSocketHandler;
import io.netty.handler.codec.http.websocketx.TextWebSocketFrame;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.listener.api.ChannelAwareMessageListener;

import java.util.HashMap;

/**
 * 点赞消息推送
 */
public class UserNoticeListener implements ChannelAwareMessageListener {
    private static final ObjectMapper MAPPER = new ObjectMapper();

    @Override
    public void onMessage(Message message, Channel channel) throws Exception {
        System.out.println("有点赞消息--------");
        try {
            String queueName = message.getMessageProperties().getConsumerQueue();
            System.out.println("queueName:"+queueName);
            System.out.println("用户列表：" + MyWebSocketHandler.userChannelMap.toString());
            String userId = queueName.substring(queueName.lastIndexOf("_") + 1);
            io.netty.channel.Channel userChannel = MyWebSocketHandler.userChannelMap.get(userId);
            if (userChannel != null){
//                Integer messageCount = message.getMessageProperties().getMessageCount();
                HashMap<String, Object> map = new HashMap<>();
                map.put("userNoticeCount",1);
                Result result = new Result(true, "推送成功", StatusCode.OK, map);
                userChannel.writeAndFlush(new TextWebSocketFrame(MAPPER.writeValueAsString(result)));
            }
        }catch (Exception e){
            System.out.println("消息发送失败！");
        }
    }
}
